package com.simba.exception;

import com.simba.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.NestedServletException;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(SQLException.class)
    public Result mySqlException(SQLException e){
        if(e instanceof SQLIntegrityConstraintViolationException){
            return Result.error().message("数据库类型转换失败！");
        }
        return Result.error().message("数据库异常，操作失败！");
    }

    @ExceptionHandler(Exception.class)
    public Result myException(Exception e){
        if(e instanceof Exception){
            return Result.error().message("程序运行异常，请检查程序！异常信息："+e.getMessage());
        }
        return Result.error().message("程序运行异常，请检查程序异常信息："+e.getMessage());
    }

    @ExceptionHandler(NestedServletException.class)
    public Result myNestedServletException(NestedServletException e){
        log.info(e.getCause().getMessage());
        return Result.error().message("程序运行异常，请检查程序异常信息："+ e.getMessage());
    }
}
